package com.woniuxy.project115.kaer.tenant.controller;


import cn.hutool.core.bean.BeanUtil;
import com.woniuxy.project115.kaer.commons.util.JwtUtil;
import com.woniuxy.project115.kaer.commons.util.Result;
import com.woniuxy.project115.kaer.commons.util.SMSUtil;
import com.woniuxy.project115.kaer.tenant.entity.TenantInfo;
import com.woniuxy.project115.kaer.tenant.form.RegisterTenantForm;
import com.woniuxy.project115.kaer.tenant.param.RegisterTenantParam;
import com.woniuxy.project115.kaer.tenant.service.TenantInfoService;
import com.woniuxy.project115.kaer.tenant.util.RedisKey;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author HuH
 * @since 2025年02月17日
 * 商家信息（账号）接口
 */
@RestController
@RequestMapping("/tenantInfo")
@Api(tags = "商家信息（账号）接口")
public class TenantInfoController {
    @Resource
    private TenantInfoService tenantInfoService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/sendRegisterCode")
    @ApiOperation("发送注册短信验证码")
    @ApiImplicitParam(name = "phone", value = "电话号码")
    public Result sendRegisterCode(String phone) throws Exception {
        tenantInfoService.sendRegisterCode(phone);
        return Result.succeed("已发送验证码");
    }

    /**
     * 注册商家账号
     * @param form 注册参数信息
     * @return
     */
    @PostMapping("/register")
    @ApiOperation("注册商家账号")
    public Result register(@RequestBody RegisterTenantForm form) throws Exception {
        tenantInfoService.register(BeanUtil.toBean(form, RegisterTenantParam.class));
        return Result.succeed("注册成功");
    }

    /**
     * @description: 商家账号登录——密码登录
     * @param phone 手机号（账号）
     * @param password 密码
     * @param response 响应
     */
    @PostMapping("/login")
    @ApiOperation("密码登录商家账号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号（账号）"),
            @ApiImplicitParam(name = "password", value = "密码")
    })
    public Result login(String phone, String password, HttpServletResponse response) throws Exception {
        TenantInfo tenantInfo = tenantInfoService.login(phone, password);
        Map<String, Object> map = BeanUtil.beanToMap(tenantInfo);
        map.remove("password");
        map.remove("cardId");
        String accessToken = JwtUtil.createToken(map, 30);
        String refreshToken = JwtUtil.createToken(map, 60 * 24 * 3);
        //生成redis key
        stringRedisTemplate.opsForValue().set(RedisKey.ACCESS_EXPIRE(accessToken), "", 60, TimeUnit.MINUTES);
        stringRedisTemplate.opsForValue().set(RedisKey.ACCESS_REFRESH(accessToken), refreshToken, 3, TimeUnit.DAYS);
        //通过响应头将jwt响应给客户端
        response.setHeader("token", accessToken);
        //在跨域请求访问时 必须公开该请求头 前端才能获取到
        response.setHeader("Access-Control-Expose-Headers","token");
        return Result.succeed("登录成功", null);
    }

    @PostMapping("/sendLoginCode")
    @ApiOperation("发送登录短信验证码")
    @ApiImplicitParam(name = "phone", value = "电话号码")
    public Result sendLoginCode(String phone) throws Exception {
        tenantInfoService.sendLoginCode(phone);
        return Result.succeed("已发送验证码");
    }

    @PostMapping("/phoneLogin")
    @ApiOperation("用户手机验证码登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号"),
            @ApiImplicitParam(name = "code", value = "验证码")
    })
    public Result phoneLogin(String phone, String code, HttpServletResponse response) throws Exception {
        TenantInfo tenantInfo = tenantInfoService.phoneLogin(phone, code);
        Map<String, Object> map = BeanUtil.beanToMap(tenantInfo);
        map.remove("password");
        map.remove("cardId");
        String accessToken = JwtUtil.createToken(map, 30);
        String refreshToken = JwtUtil.createToken(map, 3 * 24 * 60);
        stringRedisTemplate.opsForValue().set(RedisKey.ACCESS_EXPIRE(accessToken), accessToken, 30,TimeUnit.MINUTES);
        stringRedisTemplate.opsForValue().set(RedisKey.ACCESS_REFRESH(accessToken), refreshToken, 3, TimeUnit.DAYS);
        //通过响应头将jwt响应给客户端
        response.setHeader("token", accessToken);
        //在跨域请求访问时 必须公开该请求头 前端才能获取到
        response.setHeader("Access-Control-Expose-Headers","token");
        return Result.succeed("登录成功");
    }

    /**
     * @description: 修改密码
     */
    @PostMapping("/updatePassword")
    @ApiOperation("修改密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "oldPassword", value = "旧密码"),
            @ApiImplicitParam(name = "newPassword", value = "新密码"),
    })
    public Result updatePassword(String oldPassword, String newPassword, @RequestHeader String token) throws Exception {
        Integer tenantInfoId = JwtUtil.getTenantInfoId(token);
        tenantInfoService.updatePassword(tenantInfoId, oldPassword, newPassword);
        return Result.succeed("修改成功");
    }

    @PostMapping("/getState")
    @ApiOperation("获取商家状态")
    public Result getState(@RequestHeader String token) throws Exception {
        Integer tenantInfoId = JwtUtil.getTenantInfoId(token);
        return Result.succeed("success", tenantInfoService.getState(tenantInfoId));
    }

    @PostMapping("/updateState")
    @ApiOperation("修改商家状态")
    @ApiImplicitParam(name = "state", value = "状态")
    public Result updateState(@RequestHeader String token, Integer state) throws Exception {
        Integer tenantInfoId = JwtUtil.getTenantInfoId(token);
        tenantInfoService.updateState(tenantInfoId, state);
        return Result.succeed("success");
    }

    @PostMapping("/getTenantInfo")
    @ApiOperation("获取商家信息")
    public Result getTenantInfo() throws Exception {
        return Result.succeed("success", null, tenantInfoService.getTenantInfo());
    }

    @PostMapping("/getTenantInfoByToken")
    @ApiOperation("获取商家信息")
    public Result getTenantInfoByToken(@RequestHeader String token) throws Exception {
        Integer tenantInfoId = JwtUtil.getTenantInfoId(token);
        return Result.succeed("success", tenantInfoService.getTenantInfoByToken(tenantInfoId));
    }
}

